layui.use([
	'layer',
	'form',
	'carousel',
	'exconfig',
	'exrouter',
	'exutil',
	'jquery',
	'sysUser',
	'sysMenu'
], function() {

	var layer = layui.layer,
		form = layui.form,
		carousel = layui.carousel,
		exconfig = layui.exconfig,
		exrouter = layui.exrouter,
		exutil = layui.exutil,
		sysUser = layui.sysUser,
		sysMenu = layui.sysMenu,
		$ = layui.$;

	var datas = {
		isRemember: false
	};

	var elms = {
		account: $('#acc'),
		password: $('#pwd'),
		submitBtn: $('button[lay-filter="login"]')
	};

	var methods = {
		_fmtData: function(str) {
			var jsencrypt = new JSEncrypt();
			jsencrypt.setPublicKey(exconfig.winRSAPublicKey);
			// enData用来装载加密后的数据
			return jsencrypt.encrypt(str);
		},
		init: function() {
			var account = exutil.getCookie('account');
			if (account) {
				form.val("loginForm", {
					"acc": account,
					"remember": true
				});
				datas.isRemember = true;
			}

			carousel.render({
				elem: '#login_notice',
				width: '600px',
				height: '400px',
				arrow: 'always',
				arrow: 'none'
			});
		},
		clearForm: function() {
			form.val("loginForm", {
				"acc": '',
				"pwd": '',
				"remember": false
			})
		}
	};

	methods.init();

	elms.account.on('input propertychange', function(e) {
		e.stopPropagation();
		$(this).removeClass('layui-form-danger');
	});

	elms.password.on('input propertychange', function(e) {
		e.stopPropagation();
		$(this).removeClass('layui-form-danger');
	});

	form.on('checkbox(remember)', function(data) {
		datas.isRemember = data.elem.checked; //是否被选中，true或者false
	});

	form.on('submit(login)', function(data) {

		var account = data.field.acc;
		elms.submitBtn.addClass('layui-btn-disabled');
		data.field.acc = methods._fmtData(data.field.acc);
		data.field.pwd = methods._fmtData(data.field.pwd);

		sysUser.login({
				data: data.field
			})
			.done(function(resp) {

				if (datas.isRemember) {
					exutil.setCookie('account', account, {
						expires: exconfig.cookieSaveTime
					});
				} else {
					exutil.delCookie('account');
				}

				exutil.setCookie('showAccount', resp.name, {
					expires: exconfig.cookieSaveTime
				});
				exutil.setCookie('loginusertoken', resp.token, {
					expires: exconfig.cookieSaveTime
				});
				exutil.setCookie('userId', resp.id, {
					expires: exconfig.cookieSaveTime
				});
				exutil.setCookie('orgId', resp.orgId, {
					expires: exconfig.cookieSaveTime
				});
				exutil.replace(exrouter.base.home());
			})
			.always(function() {
				// methods.clearForm();
				elms.submitBtn.removeClass('layui-btn-disabled');
			});

		return false;
	});
});
